﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using EngineOfEvermore.Scene.Visual;
using EngineOfEvermore.Scene;
using EngineOfEvermore.Common;
using System.Diagnostics;

namespace EngineOfEvermore.Editor.AnimationEditor.View
{
    class WrappedLineSpriteArranger
    {
        readonly Vector2d _stride;

        public WrappedLineSpriteArranger( Vector2d stride )
        {
            _stride = stride;
        }

        public void ArrangeSprites( String staticSpriteName, 
            IEnumerable<Scene.SceneObject> sprites, RectangleF area )
        {
            Vector2d currentPosition = new Vector2d( area.Left, area.Top );
            float maxY = area.Top;
            int lineObjectCount = 0;

            foreach ( SceneObject sceneObject in sprites )
            {
                VisualComponent visualComponent = sceneObject.GetComponent<VisualComponent>();
                StaticSprite sprite = (StaticSprite) visualComponent.Children[staticSpriteName];

                Debug.Assert( sprite.PositionOffset == Vector2d.Zero );
                Debug.Assert( visualComponent.PositionOffset == Vector2d.Zero );

                Vector2d size = sprite.ScaledSize;

                if ( currentPosition.X + size.X > area.Right && lineObjectCount != 0 )
                {
                    currentPosition.X = area.Left;
                    currentPosition.Y = maxY + _stride.Y;
                    lineObjectCount = 0;
                }
                
                sceneObject.Position = currentPosition + size * 0.5f;
                
                currentPosition.X += size.X + _stride.X;

                if ( currentPosition.Y + size.Y > maxY )
                {
                    maxY = currentPosition.Y + size.Y;
                }

                ++lineObjectCount;
            }
        }
    }
}
